package com.by;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Productor {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.创建连接工厂   创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setVirtualHost("erp");//虚拟主机 默认是 /
        factory.setPort(5672); //连接端口号
        factory.setHost("192.168.203.130");//服务器地址 默认是localhost
        factory.setUsername("admin");
        factory.setPassword("123456");

        //2.创建连接  资源自动释放（连接、信道 关闭）
        try (Connection conn = factory.newConnection(); Channel channel = conn.createChannel()) {

            //3.启用发布确认
            channel.confirmSelect();

            //4.接收服务器确认的消息
            channel.addConfirmListener((deliveryTag, multiple) -> {
                System.out.println("服务器确认消息：" + deliveryTag);
            }, (deliveryTag, multiple) -> {
                System.out.println("服务器没有收到消息：" + deliveryTag);
            });

            //4.声明队列
            String queueName = "confirm-batch";
            channel.queueDeclare(queueName, false, false, false, null);


            long beign = System.currentTimeMillis();
            int batchSize = 10;//每次发送10条 等待服务器确认
            int tmp = 0;
            for (int i = 1; i <= 999; i++) {
                channel.basicPublish("", queueName, null, ("消息" + i).getBytes());
                if ((tmp = i % batchSize) == 0) {
                    channel.waitForConfirmsOrDie(5000);
                }
            }
            if (tmp > 0) {
                channel.waitForConfirmsOrDie(5000);
            }
            System.out.println("耗费时间:" + (System.currentTimeMillis() - beign));

            System.out.println("消息发布完毕，服务器已收到");
        }

    }
}